import React, { useEffect, useState } from 'react';
import { Select, Popover, Icon } from 'antd';
import { getLeaveBalance } from './service';

const { Option } = Select;

const OPTIONS = [
    {
        label: '申请调休',
        value: 1
    },
    {
        label: '申请折现',
        value: 2
    },
    {
        label: '申请抵消通知期',
        value: 3
    }
];

const Vacation = ({ dataSource, onChange, value,
    organizationCode,
    employeeCode,
    disabled = true,
    discountingTip = false }) => {
    const [commonYear, setCommonYear] = useState(0); // 剩余年假
    const [commonPaid, setCommonPaid] = useState(0); // 剩余调休

    // 获取剩余假期
    const fetchLeaveBalance = async (cId, code) => {
        const commonYearRes = await getLeaveBalance({ organizationCode: cId, employeeCode: code, leaveCode: 'CommonYear' });
        const commonPaidRes = await getLeaveBalance({ organizationCode: cId, employeeCode: code, leaveCode: 'CommonPaid' });
        if (commonYearRes.code === 10000) {
            setCommonYear(commonYearRes.data.balance);
        }

        if (commonPaidRes.code === 10000) {
            setCommonPaid(commonPaidRes.data.balance);
        }
    };

    const handleOnChange = v => {
        if (onChange) {
            onChange(v);
        }
    };

    useEffect(() => {
        if (employeeCode) {
            fetchLeaveBalance(organizationCode, employeeCode);
        }
    }, [employeeCode]);

    return (
        <div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <Select
                    disabled={disabled}
                    onChange={handleOnChange}
                    value={value}
                    {...dataSource.options}
                    style={{ flex: 1 }}
                >
                    {OPTIONS.map(o => (
                        <Option key={o.value} value={o.value}>
                            {o.label}
                        </Option>
                    ))}
                </Select>
                {discountingTip === true && (
                    <Popover
                        content={
                            <div style={{ width: 320 }}>申请折现将按劳动合同规定最高折现天数，折算为薪资发放。</div>
                        }
                        placement="top"
                        getPopupContainer={e => e.parentElement}
                    >
                        <Icon type="question-circle" style={{ marginLeft: 5, display: 'flex', alignItems: 'center' }} />
                    </Popover>
                )}
            </div>

            <p
                style={{
                    width: '100%',
                    display: 'flex',
                    marginBottom: 0,
                    marginTop: '10px'
                }}
            >
                年假{commonYear / 60 / 8 === 0 ? 0 : (commonYear / 60 / 8).toFixed(2)}天， 调休
                {commonPaid / 60 === 0 ? 0 : (commonPaid / 60).toFixed(2)}小时
            </p>
        </div>
    );
};

export default Vacation;
